package org.example.first_demo.Service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class CacheService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 从 Redis 获取数据，如果没有则模拟从 DB 获取并写入 Redis
    public String getData(String key) {
        String value = redisTemplate.opsForValue().get(key);
        if (value == null) {
            // 模拟从数据库查询
            value = "DB_DATA_" + key;
            // 存入 redis，并设置 60 秒过期
            redisTemplate.opsForValue().set(key, value, 60, TimeUnit.SECONDS);
            System.out.println("从数据库获取并写入Redis: " + value);
        } else {
            System.out.println("从Redis获取: " + value);
        }
        return value;
    }

    public void setData(String key, String value) {
        redisTemplate.opsForValue().set(key, value, 60, TimeUnit.SECONDS);
    }

    public void deleteData(String key) {
        redisTemplate.delete(key);
    }
}
